package logic

import (
	"context"
	"shell/models/mysql"

	"shell/houserpc/houserpc"
	"shell/houserpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type HouseListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewHouseListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HouseListLogic {
	return &HouseListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *HouseListLogic) HouseList(in *houserpc.HouseListRequest) (*houserpc.HouseListResponse, error) {
	// todo: add your logic here and delete this line
	offset := (in.Page - 1) * in.Size
	var houses []mysql.UserHouse
	yk := mysql.DB.Debug().Model(mysql.House{}).Offset(int(offset)).Limit(int(in.Size)).
		Select("houses.*,users.name as user_name").
		Joins("left join users on users.id=houses.user_id")
	if in.PriceOrder == 1 {
		yk = yk.Order("price desc")
	}

	if in.PriceOrder == 2 {
		yk = yk.Order("price asc")
	}

	if in.CreatedOrder == 1 {
		yk = yk.Order("created_at desc")
	}

	if in.CreatedOrder == 2 {
		yk = yk.Order("created_at asc")
	}

	if in.Start > 0 {
		yk = yk.Where("area>=?", in.Start)
	}

	if in.End > 0 {
		yk = yk.Where("area<=?", in.End)
	}
	yk.Find(&houses)
	var houseList []*houserpc.HouseList
	for _, house := range houses {
		list := houserpc.HouseList{
			UserId:     house.UserId,
			Title:      house.Title,
			Cont:       house.Cont,
			Price:      float32(house.Price),
			Address:    house.Address,
			Area:       house.Area,
			HouseImage: house.HouseImage,
			HouseId:    int64(house.ID),
			UserName:   house.UserName,
		}
		houseList = append(houseList, &list)
	}

	return &houserpc.HouseListResponse{
		List: houseList,
	}, nil
}
